package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"smart-sensor-cloud/internal/config"
	"time"
)

const (
	databaseType = "mysql"
)

var (
	db *gorm.DB
)

type (
	Model struct {
		ID        uint      `json:"id" gorm:"column:id;primaryKey;autoIncrement;not null;"`
		CreatedAt time.Time `json:"created_at" gorm:"column:created_at;not null;autoCreateTime;"`
		UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;nou null;autoUpdateTime;"`
	}
)

func ConnectDatabaseWithConfig(conf *config.DBConfig) error {
	var err error
	if db, err = gorm.Open(databaseType, conf.GetDSN()); err != nil {
		return fmt.Errorf("connect to database failed, %w", err)
	}

	db.DB().SetMaxOpenConns(conf.MaxOpen)
	db.DB().SetMaxIdleConns(conf.MaxIdle)
	db.LogMode(true)

	db.Set("gorm:table_options", "ENGINE=InnoDB")
	db.AutoMigrate(
		new(Project),
		new(Section),
		new(Device),
		new(MenuAction),
		new(ActionResource),
		new(Menu),
		new(RoleMenu),
		new(Role),
		new(UserRole),
		new(User),
		new(Host),
	)

	return nil
}
